﻿using CKS.Core.Framework;
using FreeSql;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Enums;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription {

    /// <summary>
    /// 散热片子码绑定订阅点
    /// </summary>
    [SubscribeAction("RadiatorCodeBindingSubscribe")]
    public class RadiatorCodeSubscribe : SubscribeBase {

        public RadiatorCodeSubscribe(DecodeValue decodeValue) : base(decodeValue) {

        }

        public override void ExecuteAction(Dictionary<string, object> execParams) {

            using (var ObjectCo = base.FreeSql.Ado.MasterPool.Get()) {
                var result = DecodeValue.Value.ToInt();
                var position = DecodeValue.Position;
                var conn = ObjectCo.Value;
                //回复绑定关系点位
                var replyRelBindingPos = DecodeValue.GetReplyPosition(position, actionIdFieldFilter: true, actionKeyFieldFilter: true);

                if (result == 1) {

                    //获取绑定位的条码值
                    var mainCodeBindingValue = base.GetMainCodeValue();
                    //如果条码值为空，则不进行处理
                    if (string.IsNullOrEmpty(mainCodeBindingValue)) {
                        EventBus.AddLogInfoToQueues("绑定的主产品码值为空");
                        WriteInt16(replyRelBindingPos, 99);
                        return;
                    }


                    List<CksBarcodeRelationshipRecord> codeList = new List<CksBarcodeRelationshipRecord>();
                    for (int i = 101; i <= 106; i++) {

                        eBarCodeRelType eCodeTypeValue = 0;  // 默认值
                        if (Enum.TryParse(i.ToString(), out eCodeTypeValue) && Enum.IsDefined(typeof(eBarCodeRelType), eCodeTypeValue)) {
                            // 成功转换 Do Nothing
                            Debug.WriteLine(i);
                        } else {
                            // 处理未找到匹配的情况
                            EventBus.AddLogInfoToQueues("没有找到匹配子码类型的枚举值");
                            WriteInt16(replyRelBindingPos, 2);
                            return;
                        }

                        //获取子码字段位置
                        var codePosition = DecodeValue.GetPositionByActionKey(position, $"RadiatorCode{i}");

                        if (codePosition != null) {

                            var subCodeValue = DecodeValue.GetLinkDecodeObject(codePosition).CharString.TrimEnd();

                            if (!string.IsNullOrEmpty(subCodeValue)) {

                                //验证是否重复绑定
                                var barRelRec = conn.Select<CksBarcodeRelationshipRecord>().Where(o => o.SubcodeCode == subCodeValue).ToList();
                                if (barRelRec != null && barRelRec.Any(o => !o.IsDeleted)) {
                                    EventBus.AddLogInfoToQueues($"当前子码、条码已存在绑定关系，绑定记录ID：{barRelRec.Where(o => !o.IsDeleted).FirstOrDefault().Id}");
                                    WriteInt16(replyRelBindingPos, 2);
                                    return;
                                }

                                CksBarcodeRelationshipRecord cksBarcodeRelationshipRecord = new CksBarcodeRelationshipRecord {
                                    PrimaryCode = mainCodeBindingValue,
                                    SubcodeCode = subCodeValue,
                                    PlcID = position.PlcId,
                                    Type = eCodeTypeValue,
                                    CreatedTime = DateTime.Now,
                                    ReadDB = position.BlockDb, //设置读取DB块
                                };

                                codeList.Add(cksBarcodeRelationshipRecord);

                            } else {

                                EventBus.AddLogInfoToQueues($"散热片{i}位置子码为空");
                                WriteInt16(replyRelBindingPos, 2);
                                return;

                            }

                        } else {

                            EventBus.AddLogInfoToQueues($"未配置散热片{i}绑定的条码ActionKey条码字段");
                            WriteInt16(replyRelBindingPos, 2);
                            return;

                        }
                    }

                    //插入新条码关系记录
                    var diff = conn.Insert(codeList).ExecuteAffrows();
                    if (diff <= 0) {
                        WriteInt16(replyRelBindingPos, 2);
                    }
                    WriteInt16(replyRelBindingPos, 1);
                    EventBus.AddLogInfoToQueues($"散热片子码关系绑定记录，主码：{mainCodeBindingValue}，子码：{string.Join(",", codeList.Select(o => o.SubcodeCode))}，保存绑定关系，Affrows：{diff}");

                } else {

                    WriteInt16(replyRelBindingPos, 0);
                    EventBus.AddLogInfoToQueues($"子码绑定重置");

                }
            }

        }
    }
}
